#pragma once

#include <unordered_map>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <string.h>
#include <error.h>

#include "Log.hpp"

const char* defalutpath = "resourse/dict.txt";
const static std::string Sep = " ";
const static std::string unknown = "unknown";

class Translate
{
public:
    Translate()
        :_dict_path(defalutpath)
    {
        Loaddict();
        Parse();
    }

    // 加载字典
    void Loaddict()
    {
        std::ifstream in(_dict_path.c_str(),std::ifstream::in);
        if(!in)
            lg.LogMessage(Fatal,"ifstream error , errno : %d , error string : %s\n",errno,strerror(errno));

        std::string line;
        while(getline(in,line))
        {
            _lines.push_back(line);
        }
    } 

    // 执行翻译
    std::string Execute(const std::string& word)
    {
        if(_dict.find(word) != _dict.end())
        {
            return _dict[word];
        }
        return "unknown";
    } 

    // 将读取到的一行中英文单词互译拆分为：英文和中文
    void Parse()
    {
        for(auto& line : _lines)
        {
            size_t pos = line.find(Sep);
            if(pos == std::string::npos)
            {
                continue;
            }
            std::string word = line.substr(0,pos);
            // 跳过空格
            while(line[pos] == ' ')
            {
                pos++;
            }
            std::string chinese = line.substr(pos);

            _dict.insert(std::make_pair(word,chinese));
        }
    } 

    // 用于测试
    void Debug()
    {
        for(auto& line:_lines)
        {
            std::cout << line << std::endl;
        }

        for(auto& tmp:_dict)
        {
            std::cout << tmp.first << " : " << tmp.second << std::endl;
        }
    }

    ~Translate()
    {}
private:
    std::string _dict_path;
    std::vector<std::string> _lines;
    std::unordered_map<std::string,std::string> _dict;
};